'''运维脚本'''

import os
import glob
import os
import shutil
import datetime
import logging

logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

def cleanup_folder(folder_path, max_size, max_count):
    # 获取文件夹内所有文件的路径和修改时间
    files = [(path, os.path.getmtime(path)) for path in glob.glob(os.path.join(folder_path, '*'))]

    # 根据修改时间排序，获取最早的文件
    files.sort(key=lambda x: x[1])

    # 计算文件夹当前大小
    current_size = sum(os.path.getsize(file[0]) for file in files)

    logger.info(f"{folder_path} 当前空间：{current_size}")

    if current_size > max_size:
        # 需要删除的文件总大小
        size_to_delete = current_size - max_size

        count = 0
        for file_path, _ in files:
            if count < max_count and size_to_delete > 0:
                # 删除文件
                os.remove(file_path)

                logger.info(f"删除文件：{file_path}")
                size_to_delete -= os.path.getsize(file_path)
                count += 1
            else:
                break




def backup_and_clear_logs_(log_files, max_size): # 留多份备份
    for log_file in log_files:
        if os.path.isfile(log_file):
            # 获取文件大小
            file_size = os.path.getsize(log_file) / (1024 * 1024)  # 转换为MB
            if file_size > max_size:
                # 构建备份文件路径
                backup_file = log_file + '.' + datetime.datetime.now().strftime('%Y%m%d%H%M%S')

                # 备份日志文件
                shutil.copy2(log_file, backup_file)

                # 清空原日志文件
                with open(log_file, 'w') as f:
                    f.truncate()
                
    # 重启服务的操作，可以在这里实现，根据你具体的服务和系统，可能需要不同的操作



def backup_and_clear_logs__(log_files, max_size): # 只留一份备份
    for log_file in log_files:
        if os.path.isfile(log_file):
            # 获取文件大小
            file_size = os.path.getsize(log_file) / (1024 * 1024)  # 转换为MB
            if file_size > max_size:
                # 构建备份文件路径
                backup_file = log_file + '.backup'

                # 备份日志文件，覆盖旧备份文件
                shutil.copy2(log_file, backup_file)

                # 清空原日志文件
                with open(log_file, 'w') as f:
                    f.truncate()


def backup_and_clear_logs(log_files, max_size): # 只留一份备份 不保留压缩文件 并删除压缩文件
    compressed_extensions = ['.xz', '.tar', '.gz', '.zip']
    
    for log_file in log_files:
        file_extension = os.path.splitext(log_file)[1]  # 获取文件的扩展名

        if file_extension == ".backup":

            logger.info(f"跳过备份文件：{log_file}")


            continue
        
        elif file_extension in compressed_extensions:
            # 删除压缩文件
            os.remove(log_file)
            logger.info(f"删除压缩文件：{log_file}")
            continue
            
        file_size = os.path.getsize(log_file) / (1024 * 1024)
        
        if file_size > max_size:
            backup_file = log_file + '.backup'
            # 备份日志文件，覆盖旧备份文件
            shutil.copy2(log_file, backup_file)
            logger.info(f"备份文件：{log_file}")
            with open(log_file, 'w') as f:
                f.truncate()


def get_all_files(directory):
    # 用于存储所有文件的绝对路径
    files = []
    
    # 使用 os.walk() 函数遍历目录及其子目录
    for dirpath, _, filenames in os.walk(directory):
        for filename in filenames:
            file_path = os.path.join(dirpath, filename)
            files.append(file_path)
    
    return files


if __name__ == "__main__":

    ################## 视频运维 #######################
    # 设置参数
    folder_path = '/media'  # 指定需要检查和清理的文件夹路径
    max_size = 3 * 1024 * 1024 * 1024  # 指定最大文件夹大小，单位为字节
    max_count = 30  # 指定最早的文件数量

    cleanup_folder(folder_path, max_size, max_count) 

    ################## 日志运维 #######################
    # 设置参数
    log_directory = '/var/log/'
    log_files = get_all_files(log_directory)
    max_size = 10  # 指定日志文件大小的阈值，单位为MB

    backup_and_clear_logs(log_files, max_size)
